﻿using UnityEngine;
using UnityEditor;
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class StorylineWindow : EditorWindow
{
	public string storylinePath = "Assets/Resources/Data/Storyline.asset";
	private StorylineInfo storyline;
	private List<string> players;
	
	[MenuItem("Paperclips/Data/Storyline...")]
	private static void Init()
	{
		EditorWindow.GetWindow<StorylineWindow>("Storyline");
	}

	public void OnFocus()
	{
		storyline = CreateAsset<StorylineInfo>(storylinePath);

		Dictionary<InteractiveType, List<InteractiveInfo>> allInteractives = new Dictionary<InteractiveType, List<InteractiveInfo>>();
		InteractiveManager.LoadAssetDictionary(ref allInteractives);
		players = allInteractives[InteractiveType.Player].Select(x => x.itemName).ToList();
	}
	
	private T CreateAsset<T>(string _path) where T : ScriptableObject
	{
		string folder = _path.Remove(_path.LastIndexOf("/"));
		if (!Directory.Exists(folder))
		{
			Directory.CreateDirectory(folder);
			AssetDatabase.Refresh();
		}
		
		T asset = (T)AssetDatabase.LoadAssetAtPath(_path, typeof(T));
		if (asset == null)
		{
			asset = ScriptableObject.CreateInstance<T>();
			AssetDatabase.CreateAsset(asset, _path);
			AssetDatabase.SaveAssets();
			AssetDatabase.Refresh();
			
		}
		
		return asset;
	}

	private void OnGUI()
	{
		if (storyline == null)
		{
			return;
		}

		foreach (StorylineInfo.CharacterLines line in storyline.characterLines)
		{
			EditorGUILayout.BeginVertical("box");
			{
				EditorGUILayout.BeginHorizontal();
				{
					int n = EditorGUILayout.Popup(players.IndexOf(line.character), players.ToArray());
					if (n != -1)
					{
						line.character = players[n];
					}

					if (GUILayout.Button("X", GUILayout.Width(20f)))
					{
						storyline.characterLines.Remove(line);
						break;
					}
				}
				EditorGUILayout.EndHorizontal();

				for (int i = 0; i < line.lines.Count; i++)
				{
					line.lines[i] = EditorGUILayout.TextArea(line.lines[i], GUILayout.Height(30f));
				}

				if (GUILayout.Button("Add Text", GUILayout.Width(100f)))
				{
					line.lines.Add("");
				}
			}
			EditorGUILayout.EndVertical();
		}

		if (GUILayout.Button("Add Character Text", GUILayout.Width(150f)))
		{
			storyline.characterLines.Add(new StorylineInfo.CharacterLines());
		}

		if (GUI.changed)
		{
			EditorUtility.SetDirty(storyline);
		}
	}
}
